/*
* Copyright 2010 Dovado FZ-LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#import "DovadoURLConnection.h"


@implementation DovadoURLConnection
@synthesize _timer;

- (void)connectionTimeOut:(NSTimer*)timer {
	/* TODO: Set userInfo??? */
	NSLog(@"Timeout");
	NSError *error = [[NSError alloc] initWithDomain:DOVADO_URL_CONNECTION_ERROR_DOMAIN
												 code:kDovadoURLConnectionTimedOut
											 userInfo:nil];
	//[NSDictionary dictionaryWithObjectsAndKeys: NSErrorFailingURLStringKey, @"Connection timedout", nil]
	_timer = nil;
	[_delegate connection:self didFailWithError:error];
}

-(id) initWithRequest:(NSURLRequest *)request delegate:delegate {
	[super initWithRequest: (NSURLRequest *)request delegate:self];
	_delegate = delegate;
	_timer = [NSTimer timerWithTimeInterval:20.0f target:self selector:@selector(connectionTimeOut:) userInfo:nil repeats:NO];
	[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
	return self;
}


#pragma mark NSURLConnection delegate methods
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse {
	NSLog(@"willSendRequest DovadoURLConnection");
	return [_delegate connection:self willSendRequest:request redirectResponse:redirectResponse];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	NSLog(@"didReceiveResponse DovadoURLConnection");
	[_delegate connection:self didReceiveResponse:response];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	NSLog(@"didReceiveData DovadoURLConnection");
	[_delegate connection:self didReceiveData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	NSLog(@"didFailWithError DovadoURLConnection");
	if(_timer != nil) {
		[_timer invalidate];
		_timer = nil;
	}
	[_delegate connection:self didFailWithError:error];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSLog(@"connectionDidFinishLoading DovadoURLConnection");
	if(_timer != nil) {
		[_timer invalidate];
		_timer = nil;
	}
	[_delegate connectionDidFinishLoading:self];
}

- (void)dealloc {
	[super dealloc];
}


@end
